/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.webflux.web;

import com.luter.heimdall.core.context.WebResponseHolder;
import com.luter.heimdall.core.cookie.SimpleCookie;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;

import static com.luter.heimdall.core.cookie.SimpleCookie.COOKIE_HEADER_NAME;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Reactive web response 功能实现
 * <p>
 * 实现基于 Reactive web 的请求响应功能
 *
 * @author luter
 */
public class ReactiveWebResponseHolder implements WebResponseHolder {
    private static final transient Logger log = getLogger(ReactiveWebResponseHolder.class);

    /**
     * The Response.
     */
    private ServerHttpResponse response;

    /**
     * Instantiates a new Reactive web response holder.
     *
     * @param response the response
     */
    public ReactiveWebResponseHolder(ServerHttpResponse response) {
        if (null == response) {
            throw new IllegalArgumentException("ReactiveWebResponseHolder can not be null ");
        }
        this.response = response;
    }

    @Override
    public WebResponseHolder addCookie(SimpleCookie cookie) {
        setHeader(COOKIE_HEADER_NAME, cookie.toString());
        log.debug("[addCookie]::cookie = [{}]", cookie);
        return this;
    }

    @Override
    public WebResponseHolder setStatus(int statusCode) {
        response.setStatusCode(HttpStatus.valueOf(statusCode));
        log.debug("[setStatus]::statusCode = [{}]", statusCode);
        return this;
    }

    @Override
    public WebResponseHolder setHeader(String name, String value) {
        response.getHeaders().set(name, value);
        log.debug("[setHeader]::name = [{}], value = [{}]", name, value);
        return this;
    }

    /**
     * Gets response.
     *
     * @return the response
     */
    public ServerHttpResponse getResponse() {
        return response;
    }

    /**
     * Sets response.
     *
     * @param response the response
     * @return the response
     */
    public ReactiveWebResponseHolder setResponse(ServerHttpResponse response) {
        this.response = response;
        return this;
    }
}
